import 'package:flutter/material.dart';
import 'dart:math' as math;
import '../../models/airplane_model.dart';
import '../../widgets/status_panel.dart';
import '../../widgets/path_drawing_canvas.dart';

class PathControlScreen extends StatefulWidget {
  final AirplaneModel model;

  const PathControlScreen({super.key, required this.model});

  @override
  State<PathControlScreen> createState() => _PathControlScreenState();
}

class _PathControlScreenState extends State<PathControlScreen> {
  bool _isFlying = false;
  bool _isPathDrawn = false;
  double _altitude = 20.0;
  double _speed = 5.0;
  List<Offset> _currentPath = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('路径模式'),
        actions: [
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: _showHelp,
          ),
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: _isPathDrawn ? _savePath : null,
          ),
          IconButton(icon: const Icon(Icons.folder_open), onPressed: _loadPath),
        ],
      ),
      body: Column(
        children: [
          // StatusPanel(
          //   model: widget.model,
          //   batteryLevel: 78,
          //   signalStrength: 85,
          //   altitude: _altitude,
          //   speed: _speed,
          // ),
          // 飞行状态指示
          // Container(
          //   padding: const EdgeInsets.symmetric(vertical: 8.0),
          //   color:
          //       _isFlying
          //           ? Colors.green.withOpacity(0.2)
          //           : Colors.grey.withOpacity(0.2),
          //   child: Center(
          //     child: Text(
          //       '状态: ${_isFlying
          //           ? "飞行中"
          //           : _isPathDrawn
          //           ? "路径已绘制"
          //           : "请绘制路径"}',
          //       style: TextStyle(
          //         fontWeight: FontWeight.bold,
          //         color: _isFlying ? Colors.green : Colors.grey.shade700,
          //       ),
          //     ),
          //   ),
          // ),
          // 绘图区域
          Expanded(
            child: Stack(
              children: [
                // 绘图画布
                PathDrawingCanvas(
                  onPathUpdated: (path) {
                    setState(() {
                      _currentPath = path;
                      _isPathDrawn = path.isNotEmpty;
                    });
                  },
                  enabled: !_isFlying,
                ),
                // 飞行中的飞机指示
                if (_isFlying && _currentPath.isNotEmpty)
                  AnimatedPositioned(
                    duration: const Duration(milliseconds: 500),
                    curve: Curves.easeInOut,
                    left: _currentPath.first.dx - 15,
                    top: _currentPath.first.dy - 15,
                    child: Container(
                      width: 30,
                      height: 30,
                      decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.primary,
                        shape: BoxShape.circle,
                      ),
                      child: const Icon(
                        Icons.airplanemode_active,
                        color: Colors.white,
                        size: 20,
                      ),
                    ),
                  ),
              ],
            ),
          ),
          // 控制面板
          Container(
            padding: const EdgeInsets.all(16.0),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surfaceVariant,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(16),
                topRight: Radius.circular(16),
              ),
            ),
            child: Column(
              children: [
                // 高度控制
                // Row(
                //   children: [
                //     const Text('飞行高度:'),
                //     const SizedBox(width: 8),
                //     Expanded(
                //       child: Slider(
                //         value: _altitude,
                //         min: 10,
                //         max: 100,
                //         divisions: 9,
                //         label: '${_altitude.toStringAsFixed(0)}米',
                //         onChanged: (value) {
                //           setState(() {
                //             _altitude = value;
                //           });
                //         },
                //       ),
                //     ),
                //     Text('${_altitude.toStringAsFixed(0)}米'),
                //   ],
                // ),
                // // 速度控制
                // Row(
                //   children: [
                //     const Text('飞行速度:'),
                //     const SizedBox(width: 8),
                //     Expanded(
                //       child: Slider(
                //         value: _speed,
                //         min: 1,
                //         max: 20,
                //         divisions: 19,
                //         label: '${_speed.toStringAsFixed(0)}米/秒',
                //         onChanged: (value) {
                //           setState(() {
                //             _speed = value;
                //           });
                //         },
                //       ),
                //     ),
                //     Text('${_speed.toStringAsFixed(0)}米/秒'),
                //   ],
                // ),
                // 控制按钮
                Row(
                  children: [
                    Expanded(
                      child: ElevatedButton(
                        onPressed: _isPathDrawn ? _clearPath : null,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.orange,
                          foregroundColor: Colors.white,
                        ),
                        child: const Text('清除路径'),
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: _isPathDrawn ? _toggleFlight : null,
                        style: ElevatedButton.styleFrom(
                          backgroundColor:
                              _isFlying ? Colors.red : Colors.green,
                          foregroundColor: Colors.white,
                        ),
                        child: Text(_isFlying ? '停止飞行' : '开始飞行'),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _toggleFlight() {
    setState(() {
      _isFlying = !_isFlying;
    });

    if (_isFlying) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('飞机开始按照路径飞行'),
          duration: Duration(seconds: 2),
        ),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('飞行已停止'), duration: Duration(seconds: 2)),
      );
    }
  }

  void _clearPath() {
    setState(() {
      _currentPath = [];
      _isPathDrawn = false;
      _isFlying = false;
    });
  }

  void _savePath() {
    // 模拟保存路径
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('路径已保存'), duration: Duration(seconds: 2)),
    );
  }

  void _loadPath() {
    // 模拟加载路径
    setState(() {
      // 创建一个示例路径
      final size = MediaQuery.of(context).size;
      final centerX = size.width / 2;
      final centerY = size.height / 3;
      final radius = size.width / 4;

      _currentPath = List.generate(36, (i) {
        final angle = i * 10 * 3.14159 / 180;
        return Offset(
          centerX + radius * math.cos(angle),
          centerY + radius * math.sin(angle),
        );
      });
      _isPathDrawn = true;
    });

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('示例路径已加载'), duration: Duration(seconds: 2)),
    );
  }

  void _showHelp() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('路径模式帮助'),
            content: const Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('1. 在屏幕上绘制飞行路径'),
                Text('2. 调整飞行高度和速度'),
                Text('3. 点击"开始飞行"按钮'),
                SizedBox(height: 8),
                Text('飞机将按照您绘制的路径自动飞行'),
                SizedBox(height: 8),
                Text('您可以保存常用路径或加载之前保存的路径'),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('了解'),
              ),
            ],
          ),
    );
  }
}
